package com.jflame.tomcat;

import com.jflame.tomcat.handler.JFRequestHandler;
import com.jflame.tomcat.servlet.Servlet;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-07-21
 * Time:15:10
 */
public class JFTomcat {
    static ConcurrentMap<String, String> servletUrlMap = new ConcurrentHashMap<>();
    static ConcurrentMap<String, String> servletPathMap = new ConcurrentHashMap<>();
    static ConcurrentMap<String, Servlet> servletMap = new ConcurrentHashMap<>();
    public static void main(String[] args) {
        JFTomcat tomcat = new JFTomcat();
        //tomcat.init();
        tomcat.run();
    }
    public void init() {
        SAXReader reader = new SAXReader();
        String file = Objects.requireNonNull(JFTomcat.class.getResource("/")).getFile();
        try {
            reader.read(new File(file + "web.xml"));
        } catch (DocumentException | MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }
    public void run() {
        ServerSocket serverSocket;
        try {
            serverSocket = new ServerSocket(8081);
            while (serverSocket.isBound()) {
                Socket socket = serverSocket.accept();
                System.out.println("client connected");
                JFRequestHandler handler = new JFRequestHandler(socket);
                new Thread(handler).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
